<template>
  <div>
    <ContentWrap>
      <superSeach @search="doSearch" :is-loading="isLoading" :defaultVal="defaultVal" />
    </ContentWrap>
    <ContentWrap>
      <div class="crm-workbench__body" v-loading="isLoading">
        <div class="form-title" ref="listTitleRef">
          <Flexbox justify="space-between">
            <el-text>
              为您找到
              <el-text type="primary">{{ totals }}</el-text>
              家企业
              <template v-if="totals == 10000">
                <div>
                  <span v-if="!noTip" class="text-12px"
                    >当前查询数量不代表实际结果，仅表示优先显示的数量</span
                  >
                  <span v-if="!noTip" @click="onNoTip" class="ml-4px text-14px cursor-pointer"
                    >x</span
                  >
                </div>
              </template>
            </el-text>

            <div class="unlock-box">
              <el-button
                :disabled="!dataList.length"
                type="primary"
                :icon="Unlock"
                @click="onClickUnlock"
              >
                批量领取
              </el-button>
            </div>
          </Flexbox>
        </div>
        <div class="page-box">
          <company-list
            :list="dataList"
            style="width: 100%"
            @refresh-val="refreshData"
            @show-item="onEntNameClick"
          />
        </div>
        <Flexbox justify="flex-end" style="margin: 10px 0">
          <Pagination
            v-model:limit="pageSize"
            v-model:page="pageNo"
            :total="totals"
            @pagination="paginaSet"
          />
        </Flexbox>
      </div>
    </ContentWrap>
    <TableSelect
      :modelValue="selectedItems"
      ref="tableSelect"
      @update:model-value="receiveCompany"
      @get-table-fun="getTableFun"
    >
      <el-table-column prop="companyInfo.companyName" label="企业名称" align="center" />
      <el-table-column prop="companyInfo.numberCount" label="联系电话(条)" align="center" />
      <el-table-column label="解锁状态" align="center">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.companyInfo.received"
            >已被{{ scope.row.companyInfo.receiveUser }}领取</el-tag
          >
          <el-tag type="primary" v-else>待领取</el-tag>
        </template>
      </el-table-column>
    </TableSelect>
    <!-- 企业详情 -->
    <EnterpriseDetails ref="companyDetail" @refresh-val="detailRefreList" />
  </div>
</template>
<script setup lang="ts">
import superSeach from './superSearch/index.vue'
import CompanyList from './CompanyList.vue'
import { Refresh, Unlock } from '@element-plus/icons-vue'
import { useEntStore } from '@/store/modules/ent'
import * as advanceApi from '@/api/ent/advanceSearch/index'
import { ElMessage } from 'element-plus'
import EnterpriseDetails from '../components/EnterpriseDetaill/index.vue'
const route = useRoute()
const defaultVal = ref({})

const isLoading = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const totals = ref(0)
const dataList = ref([])
const entStore = useEntStore()
const refreshValue = ref(null)
const tableSelect = ref(null)
const companyDetail = ref(null)
const selectedItems = ref([])

const noTip = ref(localStorage.getItem('ent_no_tip'))
const onNoTip = () => {
  noTip.value = true
  localStorage.setItem('ent_no_tip', true)
}
onBeforeMount(async () => {
  await entStore.setAdvanceCond()
})
onMounted(() => {
  const { query } = route
  if (query.keyword) {
    defaultVal.value = JSON.parse(sessionStorage.getItem('useTemplate'))
    doSearch(defaultVal.value)
  }
})
// 搜索
const doSearch = async (val) => {
  const limit = processData(val)
  pageNo.value = 1
  let data = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    operations: [limit]
  }
  refreshValue.value = data
  isLoading.value = true
  doRequest(data)
}

// 详情刷新
const detailRefreList = (data) => {
  let index = sessionStorage.getItem('companyIndex')
  dataList.value[index].companyInfo.receiveUser = data.receiveUser
  dataList.value[index].companyInfo.received = data.received
}

// 刷新/分页切换
const refreshData = () => {
  if (refreshValue.value) {
    isLoading.value = true
    doRequest(refreshValue.value)
  }
}
// 数据请求
const doRequest = async (data) => {
  const { results, total } = await advanceApi.companyGetList(data).finally(() => {
    isLoading.value = false
  })
  totals.value = total
  let ids
  if (results.length) {
    ids = results.map((element) => element.companyInfo.cid)
    const res = await advanceApi.companyGetStatus({ ids: ids })
    dataList.value = mergeValues(results, res)
  } else {
    dataList.value = results
    ElMessage.warning('暂无数据')
  }
}

// key
const mergeValues = (arrayA, objectB) => {
  arrayA.forEach((itemA) => {
    let key = itemA.companyInfo.cid
    if (objectB[key]) {
      Object.assign(itemA.companyInfo, objectB[key])
    }
  })
  return arrayA
}

// 处理数据
const processData = (data) => {
  let obj = JSON.parse(JSON.stringify(data))
  obj.operations = []
  obj = moveQueryFieldsToOperations(obj)
  // 处理行业只需最后一个
  obj.queryFields.forEach((item) => {
    if (item.field == 'industry') {
      item.value = item.value.map((spliceArr) => {
        if (spliceArr.length == 2) {
          return spliceArr.splice(1, 1)
        }
      })
      item.value = item.value.filter((init) => init !== undefined)
      item.value = item.value.join(',')
    } else if (Object.prototype.toString.call(item.value) === '[object Array]') {
      if (item.queryType == 'range' || item.queryType == 'range_date') {
        item.value = item.value.join(',')
      } else {
        item.value = item.value
          .map((subArr) => {
            if (subArr.indexOf('/') == -1) {
              return subArr
            } else {
              return subArr.join('/')
            }
          })
          .join(',')
      }
    }
  })
  // 处理组合条件
  obj.operations.forEach((items) => {
    items.queryFields.forEach((item) => {
      if (item.field == 'industry') {
        item.value = item.value.map((spliceArr) => {
          if (spliceArr.length == 2) {
            return spliceArr.splice(1, 1)
          }
        })
        item.value = item.value.filter((init) => init !== undefined)
        item.value = item.value.join(',')
      } else if (Object.prototype.toString.call(item.value) === '[object Array]') {
        if (item.queryType == 'range' || item.queryType == 'range_date') {
          item.value = item.value.join(',')
        } else {
          item.value = item.value
            .map((subArr) => {
              if (subArr.indexOf('/') == -1) {
                return subArr
              } else {
                return subArr.join('/')
              }
            })
            .join(',')
        }
      }
    })
  })
  return obj
}
// 组合条件处理
const moveQueryFieldsToOperations = (data) => {
  if (Array.isArray(data)) {
    data.forEach((item) => {
      if (item.queryFields) {
        item.operations = item.operations || []
        item.operations.push(...item.queryFields.filter((field) => field.queryFields))
        item.queryFields = item.queryFields.filter((field) => !field.queryFields)
      }
      if (item.operations) {
        moveQueryFieldsToOperations(item.operations)
      }
    })
  } else if (data && typeof data === 'object') {
    Object.keys(data).forEach((key) => {
      if (key === 'queryFields') {
        data.operations = data.operations || []
        data.operations.push(...data.queryFields.filter((field) => field.queryFields))
        data.queryFields = data.queryFields.filter((field) => !field.queryFields)
      } else {
        moveQueryFieldsToOperations(data[key])
      }
    })
  }
  return data
}
//显示弹窗
const onClickUnlock = () => {
  tableSelect.value.openDialogVisible({
    value: dataList.value,
    totals: totals.value,
    pageNo: refreshValue.value.pageNo,
    pageSize: refreshValue.value.pageSize
  })
}
// 表格分页
const getTableFun = async (val) => {
  refreshValue.value.pageNo = val.pageNo
  refreshValue.value.pageSize = val.pageSize
  pageNo.value = val.pageNo
  pageSize.value = val.pageSize
  let data = { ...refreshValue.value }
  await doRequest(data)
  onClickUnlock()
}
// 批量解锁
const receiveCompany = async (val) => {
  let ids = []
  if (val.length) {
    val.forEach((item) => {
      ids.push(item.companyInfo.cid)
    })
    const res = await advanceApi.companyReceive({ ids })
    if (res) ElMessage.success('解锁成功!')
    refreshData()
  }
}
// 数据分页
const paginaSet = (val) => {
  const { page, limit } = val
  refreshValue.value.pageNo = page
  refreshValue.value.pageSize = limit
  refreshData()
}
// 详情
const onEntNameClick = async (item, val, index) => {
  //                            显示             cid        锚点?  下标
  companyDetail.value.setDrawer(true, item.companyInfo.cid, val, index)
}
</script>
<style scoped lang="scss">
.crm-workbench__body {
  max-width: 80%;
  margin: 0 auto;
}
.unlock-box {
  $text-fontSize: 12px;
  .el-button {
    font-size: $text-fontSize;
  }
  .el-text {
    font-size: $text-fontSize;
    color: #c0c4cc;
    margin-left: 5px;
  }
}
.crm-workbench {
  overflow: hidden;
  overflow-y: auto;

  &__body {
    background: #ffffff;

    .form-title {
      color: #172b4d;
      padding: 0 0 20px 0;
      border-bottom: 1px solid #eff3f6;
    }

    .el-button.mini {
      padding: 4px 10px;
      font-size: 12px;
    }

    .page-box {
      padding-top: 10px;
      width: 100%;
      overflow: hidden;
      margin: 0 auto;
    }
  }
}
</style>
